/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package data.xml_persistence.logic;

import data.xml_persistence.model.DataModel;

import java.io.IOException;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.ValidationException;
import org.xml.sax.InputSource;

import java.io.FileReader;
import java.io.FileWriter;

/**
 *
 * @author ded_end
 */
public class XMLTransformer {

    private static final String MAP = "mapping.xml";

    public static data.EntityContainer unmarshal(String fileName) throws IOException {
        try {
            Mapping mapping = new Mapping();
            DataModel model = null;

            mapping.loadMapping("mapping.xml");
            Unmarshaller unmar = new Unmarshaller(mapping);
            model = new DataModel();
            model = (DataModel) unmar.unmarshal(new InputSource(new FileReader(fileName)));

            return DataTransformer.transformToObjects(model);
        } catch (MarshalException ex) {
            Logger.getLogger(XMLTransformer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ValidationException ex) {
            Logger.getLogger(XMLTransformer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MappingException ex) {
            Logger.getLogger(XMLTransformer.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public static void marshal(data.EntityContainer entityContainer, String fileName) {
        Mapping mapping = new Mapping();
        FileWriter writer = null;
        DataModel model = DataTransformer.transformToXML(entityContainer);
        try {
            mapping.loadMapping(MAP);

            writer = new FileWriter(fileName);

            Marshaller marshaller = new Marshaller(writer);
            marshaller.setMapping(mapping);
            marshaller.marshal(model);
        } catch (Exception e) {
            System.out.println(e);
            return;
        }
    }
}
